/**
 *       Copyright (c) 2011 Lukas Zaruba
 * 
 *   This file is part of ParPortTester
 *
 *   ParPortTester is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   ParPortTester is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with ParPortTester. If not, see <http://www.gnu.org/licenses/>.
 */


package net.zarubsys.parporttester.dynResp;

import java.lang.reflect.InvocationTargetException;

import net.zarubsys.parporttester.core.resp.OutputTestResultWithResp;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.SWT;

/**
 * @author  &lt;A HREF=&quot;mailto:lukas.zaruba@gmail.com&quot;&gt;Lukas Zaruba&lt;/A&gt; zarubsys.net
 */
public abstract class AbstractRespWizard extends Wizard {
	
	private static final String ERROR_PATTERN = Messages.AbstractRespWizard_result_error;
	private static final String OK_PATTERN = Messages.AbstractRespWizard_result_ok;

	@Override
	public boolean performFinish() {
		OutputTestResultWithResp result = new OutputTestResultWithResp();
		IRunnableWithProgress runnable = prepareRunnable(result);
	    try {
	            getContainer().run(true, true, runnable);
	    } catch (InterruptedException e) {
	            return false;
	    } catch (InvocationTargetException e) {
	            Throwable realException = e.getTargetException();
	            MessageDialog.openError(getShell(), Messages.AbstractRespWizard_result_title_error, realException.getMessage());
	            return false;
	    }
	    
	    String pattern = result.isFinishedNormally() ? OK_PATTERN : ERROR_PATTERN;
	    String message = String.format(pattern, result.getRepetitionsDone(), result.getDuration(), result.getChangesCount(), result.getTimeToFirstInput());
	    int kind = result.isFinishedNormally() ? MessageDialog.INFORMATION : MessageDialog.WARNING;
		MessageDialog.open(kind, getShell(), Messages.AbstractRespWizard_result_title_ok, message, SWT.NONE);
	    return true;
	}

	abstract protected IRunnableWithProgress prepareRunnable(OutputTestResultWithResp result);

}
